package com.dcd.util;

import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class SolrUtil {

    @Autowired
    private SolrClient solrClient;

    /**
     * 在指定collection中搜索数据
     *
     * @param conditions
     * @return
     */
    public Map<String, Object> solr_content_by_collection(Map<String, Object> conditions) throws IOException, SolrServerException {
        HashMap<String, Object> result_map = new HashMap<>();
        String solr_content = conditions.get("solr_content").toString();//搜索关键字
        String collection = conditions.get("collection").toString();//核心名称
        String highlight_field = conditions.get("highlight_field").toString();//高亮字段
        int page_index = Integer.parseInt(conditions.get("page_index").toString());//当前页数
        String[] all_fields = (String[]) conditions.get("all_fields");//显示字段集合

        SolrQuery solrQuery = new SolrQuery();
        // 设置查询关键字
        solrQuery.setQuery(highlight_field + ":" + solr_content);
        // 结果中域的列表
        solrQuery.setFields(all_fields);
        solrQuery.setHighlight(true); // 开启高亮
        solrQuery.addHighlightField(highlight_field); // 高亮字段
        solrQuery.setHighlightSimplePre("<span style='color:red'>"); // 高亮单词的前缀
        solrQuery.setHighlightSimplePost("</span>"); // 高亮单词的后缀
        //分页
        solrQuery.setStart((page_index - 1) * 12);//起始index
        solrQuery.setRows(12);//行数
        solrQuery.setHighlightFragsize(100);
        QueryResponse query = solrClient.query(collection, solrQuery);
        SolrDocumentList results = query.getResults();
        for (SolrDocument solrDoc : results) {
            Map<String, Map<String, List<String>>> highlighting = query.getHighlighting();
            List<String> list = highlighting.get(solrDoc.get("id")).get(highlight_field);
            if (list != null && list.size() > 0)
                solrDoc.setField(highlight_field, list.get(0));
        }
        int total = (int) results.getNumFound();
        result_map.put("pages", total % 12 == 0 ? total / 12 : total / 12 + 1);
        result_map.put("result", results);
        return result_map;
    }
}
